<?php
/**
 * 伙拼类
 * @author 志杨
 *
 */
class Huopin
{
	var $db;
	
	function __construct()
	{
		global $db;
		
		$this -> db     = & $db;
	}
	
	/**
	 * 伙拼完成后把已支付的订单商品放入用户微仓
	 * @param unknown $hpId
	 */
	public function updateMicroStockAfterSuccess($hpId)
	{
	    if($hpId>0){
	        $sql = "select order_id,stock_shop from ".HUOPINORDER." where hp_id={$hpId} and status>=2";
	        $this->db->query($sql);
	        $orderList = $this->db->getRows();
	        if(!empty($orderList)){
	            foreach ($orderList as $v)
	            {
	                $this->updateMicroStock($v['order_id'], $v['stock_shop']);
	            }
	            return true;
	        }
	        return false;
	    }
	}
	
	/**
	 * 更新用户微仓商品
	 * @param unknown $orderId
	 * @param unknown $stockShop
	 */
	public function updateMicroStock($orderId,$stockShop)
	{
	    if($orderId){
	        $sql = "select a.*,b.pid from ".HUOPINORDERPRO." AS a left join ".HUOPINORDER." AS b on a.order_id=b.order_id where a.order_id={$orderId}";
	        $this->db->query($sql);
	        $productList = $this->db->getRows();
	        if(!empty($productList)){
	            //写入微仓订单
	            $sql = "select * from ".HUOPINORDER." where order_id={$orderId} limit 1";
	            $this->db->query($sql);
	            $orderInfo = $this->db->fetchRow();
	            $status = $this->insertMicroOrderInfo($orderInfo,$productList);
	            
	            if($status){
    	            foreach ($productList as $val)
    	            {
    	                $sql = "select id from ".MICROSTOCK." where member_id={$val['member_id']} and sku_id={$val['sku_id']} and pid={$val['pid']}";
    	                $this->db->query($sql);
    	                $microStockId = $this->db->fetchField('id');
    	                if($microStockId>0){//微仓有这个商品，更新
    	                    $sql = "update ".MICROSTOCK." set num=num+{$val['num']} where id={$microStockId}";
    	                    $this->db->query($sql);
    	                }else{//无则新增
    	                    $time = date('Y-m-d H:i:s',time());
    	                    $sql = "insert into ".MICROSTOCK." (`member_id`,`stock_shop`,`sku_id`,`pid`,`num`,`create_time`) values('{$val['member_id']}','{$stockShop}','{$val['sku_id']}','{$val['pid']}','{$val['num']}','{$time}')";
    	                    $this->db->query($sql);
    	                }
    	                
    	                //减前台库存
    	                $this->db->query("update ".SETMEAL." set stock = stock-{$val['num']},sell_amount=sell_amount+{$val['num']} where id={$val['sku_id']}");
    	            }
	            }
	        }
	        
	        return true;
	    }
	    return false;
	}
	
	/**
	 * 写微仓订单
	 * @param array $orderInfo
	 * @param array $products
	 */
	private function insertMicroOrderInfo($orderInfo=array(),$products=array())
	{
	    if(!empty($orderInfo) && $orderInfo['member_id']>0){
	        $userId = $orderInfo['member_id'];
    	    //新的订单号rule 微仓
    	    $d=getdate();
    	    $prefix= 800+date('y');
    	    $prefix.=$d['yday']+200;
    	    $prefix.= time()- strtotime(date('Y-m-d'))+10000;
    	    
    	    $order_id=$prefix.str_pad(substr($userId,-3,3),3,0,STR_PAD_LEFT).rand(0,9);
	    
    	    //订单表
    	    $hp_order_id = $orderInfo['order_id'];
    	    $orderInfo['order_id'] = $order_id;
    	    $orderInfo['pay_status'] = $orderInfo['payment_status'];
    	    unset($orderInfo['payment_status']);
    	    unset($orderInfo['hp_id']);
    	    unset($orderInfo['id']);
    	    unset($orderInfo['pid']);
    	    $orderInfo['admin_remark'] = "伙拼成功，后台自动写入";
    	    $orderKey = array_keys($orderInfo);
    	    $sqlKey = implode(',', $orderKey);
    	    $sqlValue = "";
    	    foreach ($orderKey as $k)
    	    {
    	        $sqlValue .= "'{$orderInfo[$k]}',";
    	    }
    	    $sqlValue = trim($sqlValue,',');
    	    $sql = "insert into ".MICROSTOCKORDER." ({$sqlKey},`hp_order_id`) values($sqlValue,'{$hp_order_id}')";
    	    $this->db->query($sql);
    	    
    	    //订单商品表
    	    if(!empty($products)){
        	    $sql = "insert into ".MICROSTOCKORDERPRO." (`order_id`,`member_id`,`sku_id`,`pcatid`,`product_name`,`property`,`pic`,`price`,`num`,`create_time`) values ";
        	    $value = "";
        	    foreach ($products as $val)
        	    {
        	        $val['product_name'] = @mysql_escape_string($val['product_name']);
        	        $value .= ",('{$order_id}','{$val['member_id']}','{$val['sku_id']}','{$val['pcatid']}','{$val['product_name']}','{$val['property']}','{$val['pic']}','{$val['price']}','{$val['num']}','{$val['create_time']}')";
        	    }
        	    $value = trim($value,',');
        	    $sql .= $value;
        	    
        	    $this->db->query($sql);
    	    }
    	    return true;
	    }
	    return false;
	}
	
	/**
	 * 取消伙拼未支付的订单
	 * @param unknown $hpId 伙拼ID
	 */
	public function cancelNonPaymentOrder($hpId) {
	    //查询伙拼所有未支付订单
	    if($hpId>0){
	        $sql = "select order_id from ".HUOPINORDER." where hp_id={$hpId} and status=1";
	        $this->db->query($sql);
	        $orderList = $this->db->getRows();
	        if(!empty($orderList)){
	            foreach ($orderList as $v)
	            {
	                $this->cancelHpOrder($v['order_id'],'设置伙拼状态为备货时，自动取消未支付的订单');
	            }
	            return true;
	        }
	        return false;
	    }
	    return false;
	}
	
	/**
	 * 取消伙拼订单
	 * @param unknown $orderId 订单ID
	 * @param unknown $remark 备注
	 */
	public function cancelHpOrder($orderId,$remark=""){
	    //查询伙拼ID
	    $sql = "select hp_id from ".HUOPINORDER." where order_id='{$orderId}'";
	    $this->db->query($sql);
	    $hp_id = $this->db->fetchField('hp_id');
	    if($hp_id){
    	    $sql="update ".HUOPINORDER." set admin_remark='$remark',status='0' where order_id='".$orderId."'";
    	    $this->db->query($sql);
    	    /*******取消后把库存加回去和销量减掉**********/
    	    //查询订单商品
    	    $sql = "select sku_id,num from ".HUOPINORDERPRO." where order_id={$orderId}";
    	    $this->db->query($sql);
    	    $products = $this->db->getRows();
    	    if(!empty($products)){
    	        foreach ($products as $v)
    	        {
    	            $this->updateHpStocksAndAmounts($hp_id, $v['sku_id'],$v['num']);
    	        }
    	    }
    	    return true;
	    }
        return false;	    
	}
	
	/**
	 * 更新伙拼商品库存和伙拼销量
	 * @param unknown $hpId
	 * @param unknown $skuId
	 * @param unknown $num
	 */
	private function updateHpStocksAndAmounts($hpId,$skuId,$num=0){
	    $sql = "select id from ".HUOPINSKU." where hp_id={$hpId} and sku_id={$skuId}";
	    $this->db->query($sql);
	    $id = $this->db->fetchField('id');
	    $num = intval($num);
	    if($id>0 && $num>0){
	        $sql = "update ".HUOPINSKU." set hp_stock=hp_stock+{$num},hp_amount=hp_amount-{$num} where id={$id}";
	        $this->db->query($sql);
	        return true;
	    }
	    return false;
	}
	
	/**
	 * 更新订单状态
	 * @param unknown $orderId
	 * @param integer $status
	 * @param array   $arr
	 */
	public function updateOderStatus($orderId,$status,$arr=array())
	{
	    switch ($status)
	    {
	        case 2://付款
	            $sql = "update ".HUOPINORDER." set payment_id={$arr['payment_id']},payment_name='{$arr['payment_name']}',admin_remark='{$arr['admin_remark']}' where order_id={$orderId}";
	            $this->db->query($sql);
            default:
                return false;
                break;
	    }
	    
	    return true;
	}
	
	/**
	 * 获取销售额
	 * @param string $cond
	 * @param number $timeType 1为今天数据，2为昨天数据，3为本月数据
	 */
	public function getSalesInfo($cond="",$timeType=3) {
	    if(!empty($cond)){
	        $str = $cond;
	    }else{
	        $str = " and a.status>1";
	        switch ($timeType)
	        {
	            case 1://今天
	                $time = date('Y-m-d');
	                $str .= " and a.order_time>='{$time}'";
	                break;
	            case 2://昨天
	                $time = date('Y-m-d',strtotime('-1 day'));
	                $rtime = $time." 23:59:59";
	                $str .= " and a.order_time>='{$time}' and a.order_time<='{$rtime}'";
	                break;
	            case 3://本月
	                $time = date('Y-m');
	                $str .= " and a.order_time>='{$time}'";
	                break;
	            default://全部
	                break;
	        }
	    }
	    
	    $sql = "select sum(total_price) as total from ".HUOPINORDER." as a left join ".HUOPIN." as b on a.hp_id=b.id left join ".MEMBER." as m on a.member_id=m.userid where 1 {$str}";
	    $this->db->query($sql);
	    $total = $this->db->fetchField('total');
	
	    return $total?$total:0;
	}
	
	/**
	 * 获取销售订单数量
	 * @param number $shopId 仓库ID
	 * @param number $timeType 1为今天数据，2为昨天数据，3为本月数据
	 */
	public function getOrderNum($shopId=0,$timeType=3) {
	    $str = " status>1";
	    if($shopId>0){
	        $str .= " and stock_shop={$shopId} ";
	    }
	    switch ($timeType)
	    {
	        case 1://今天
	            $time = date('Y-m-d');
	            $str .= " and order_time>='{$time}'";
	            break;
	        case 2://昨天
	            $time = date('Y-m-d',strtotime('-1 day'));
                $rtime = $time." 23:59:59";
	            $str .= " and order_time>='{$time}' and order_time<='{$rtime}'";
	            break;
	        case 3://本月
	            $time = date('Y-m');
	            $str .= " and order_time>='{$time}'";
	            break;
	        default://全部
	            break;
	    }
	    
	    $sql="select count(*) as total from ".HUOPINORDER." where {$str}";
	    $this->db->query($sql);
	    $total = $this->db->fetchField('total');
	     
	    return $total?$total:0;
	}
}
?>